package com.mvc.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.action.ActionView;
import com.mvc.common.BeanUtil;
import com.mvc.common.MvcUtil;
import com.mvc.form.ActionForm;
import com.mvc.login.LoginAction;


public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActionServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ActionForm form = BeanUtil.fixBean(request);
		String actionClass = request.getServletPath().split("/")[1];
		String methodName = MvcUtil.replaceFirstToUpperCase(actionClass.split("\\.")[0]);
		HashMap<String,String> map = (HashMap<String,String>)request.getServletContext().getAttribute(MvcUtil.APPLITION_MVC_MAPPING);
		String className = map.get(actionClass);
		
//		String className = ActionMap.getActionMap(request.getParameter("valueClass"));
		try {
			Class cls = Class.forName(className);
			Object obj = cls.newInstance();
			ActionView actionView = null; 
			if(obj instanceof LoginAction){
				System.out.println("LoginAction instance!");
//				actionView = ((LoginAction)obj).execute(request,response,form);
				actionView = (ActionView)((LoginAction)obj).getClass().getMethod(methodName, new Class[]{HttpServletRequest.class,HttpServletResponse.class,ActionForm.class}).invoke(((LoginAction)obj), new Object[]{request,response,form});
			}
			
			fixAttribute(request,actionView);
			
			String path = map.get(actionView.getPath());
			RequestDispatcher rd = this.getServletContext().getRequestDispatcher(path);
			rd.forward(request, response); 
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/error.jsp");
			rd.forward(request, response); 
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

	 private void fixAttribute(HttpServletRequest request, ActionView actionView){
		 HashMap<String,Object> map = actionView.getAttrMap();
//		 System.out.println(map);
		 Set keySet = map.keySet();
		 Iterator i = keySet.iterator();
		 while(i.hasNext()){
			 String key = (String)i.next();
			 Object obj = map.get(key);
			 request.setAttribute(key, obj);
		 }
	 }
}
